'use strict';

angular.module('oaApp')
  .controller('ProjectsCtrl', function ($scope, $http, Auth) {
    $scope.projects = [];
    $scope.orderByField = 'created_at';
    $scope.reverseSort = true;
    $scope.currentUser = Auth.getCurrentUser();

    $http.get('/api/projects').success(function (res) {
      $scope.projects = res;
    });

  })
  .controller('ProjectsAddCtrl', function ($scope, $http, User, $state) {
    $scope.users = User.query();
    $scope.project = {};
    $scope.project.joiners = [];
    $scope.departments = [];

    $scope.departmentGroup = function (item){
      console.log(item);
      return item.department.name;
    };

    $http.get('/api/departments').success(
      function(departments) {
        $scope.departments = departments;
      }
    );

    $scope.create = function () {
      console.log($scope.project);
      var project = angular.copy($scope.project);
      $http.post('/api/projects', project).success(function (res) {
        console.log(res);
        $state.go('app.projects');
      }).error(function (err) {
        console.log(err);
      });
    };
  })
  .controller('ProjectsDetailCtrl', function ($scope, $http, $stateParams, $upload,Auth) {
    $scope.project = {};
    $scope.progress = false;
    $scope.nowProgress = 0;
    $scope.depart_share = false;
    $scope.currentUser = Auth.getCurrentUser();

    Array.prototype.contains = function(obj) {
      var i = this.length;
      while (i--) {
        if (this[i] === obj) {
          return true;
        }
      }
      return false;
    }

    $http.get('/api/projects/' + $stateParams.projectId).success(function (res) {
      $scope.project = res;
      //console.log(res.departments);
      //console.log($scope.depart_share);
    });
    $http.get('/api/projects/' + $stateParams.projectId+'/show').success(function (res) {
      $scope.depart_share = res.joiners.contains(Auth.getCurrentUser()._id);
    });

    $scope.removeFile = function(id, idx) {
      if(confirm('你确定删除该文件吗？')){
        $http.delete('/api/documents/'+id).success(function () {
          console.log('删除成功');
          $scope.project.files.splice(idx, 1);
        }).error(function () {
          console.log('删除失败');
        });
      }
    };
    var currentProject = {
      user: {
        _id: Auth.getCurrentUser()._id,
        name: Auth.getCurrentUser().name,
        department: Auth.getCurrentUser().department.name,
        role: Auth.getCurrentUser().role
      },
      projectId: $stateParams.projectId
    };
    $scope.upload = function () {
      $upload.upload({
        url: '/api/documents', // upload.php script, node.js route, or servlet url
        method: 'POST',
        headers: {'Content-Type': 'multipart/form-data'}, // only for html5
        //withCredentials: true,
        data: currentProject,
        file: $scope.projectFile // single file or a list of files. list is only for html5
        //fileName: 'doc.jpg' or ['1.jpg', '2.jpg', ...] // to modify the name of the file(s)
        //fileFormDataName: myFile, // file formData name ('Content-Disposition'), server side request form name
        // could be a list of names for multiple files (html5). Default is 'file'
        //formDataAppender: function(formData, key, val){}  // customize how data is added to the formData.
        // See #40#issuecomment-28612000 for sample code

      }).progress(function (evt) {
        $scope.progress = true;
        $scope.nowProgress = parseInt(100.0 * evt.loaded / evt.total) + '%';
        $scope.progressStatus = '上传中！';
        console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total) + '% file :'+ evt.config.file.name);
      }).success(function (data, status, headers, config) {
        // file is uploaded successfully
        $scope.progress = false;
        $scope.nowProgress = '0%';
        $scope.progressStatus = '上传成功！';
        console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
        $scope.project.files.push(data);
        console.log(data);
      })
      .error(function (err) {
          console.log(err);
        });
    }
        //.then(success, error, progress); // returns a promise that does NOT have progress/abort/xhr functions
        //.xhr(function(xhr){xhr.upload.addEventListener(...)}) // access or attach event listeners to
        //the underlying XMLHttpRequest
      /* alternative way of uploading, send the file binary with the file's content-type.
       Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed.
       It could also be used to monitor the progress of a normal http post/put request.
       Note that the whole file will be loaded in browser first so large files could crash the browser.
       You should verify the file size before uploading with $upload.http().
       */
      // $scope.upload = $upload.http({...})  // See 88#issuecomment-31366487 for sample code.


  })
  .controller('ProjectsEditCtrl', function ($scope, $http, $state, Auth, $stateParams, Modal) {
    $scope.project = {};
    $scope.departments = [];
    $scope.currentUser = Auth.getCurrentUser();

    Array.prototype.contains = function(obj) {
      var i = this.length;
      while (i--) {
        if (this[i] === obj) {
          return true;
        }
      }
      return false;
    };

    $http.get('/api/departments')
      .success(function(departments) {
        $scope.departments = departments;
      });

    $http.get('/api/projects/'+$stateParams.projectId+'/edit').success(function (res) {
      $scope.project = res;
      $scope.depart_share = res.joiners.contains(Auth.getCurrentUser()._id);
      if(!$scope.depart_share && Auth.getCurrentUser().department.name != '综合部'){
        alert('对不起，你们有权限修改项目');
        $state.go('app.projects');
      }
    });

    $scope.update = function () {
      var project = angular.copy($scope.project);
      console.log(project);
      $http.put('/api/projects/'+$stateParams.projectId, project).success(function (res) {
        //alert('更新成功');
        console.log(res);
        $state.go('app.projects');
      });
    };

    $scope.delete = Modal.confirm.delProject(function () {
      $state.go('app.projects');
    });

  })
  .filter('propsFilter', function() {
    return function(items, props) {
      var out = [];

      if (angular.isArray(items)) {
        items.forEach(function(item) {
          var itemMatches = false;

          var keys = Object.keys(props);
          for (var i = 0; i < keys.length; i++) {
            var prop = keys[i];
            var text = props[prop].toLowerCase();
            if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
              itemMatches = true;
              break;
            }
          }

          if (itemMatches) {
            out.push(item);
          }
        });
      } else {
        // Let the output be the input untouched
        out = items;
      }

      return out;
    };
  });
